<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity
{
    /**
     * Authenticates a user.
     * The implementation below takes a username and plain-text
     * password submitted by the user. It then retrieves a row from
     * the Users table in the database based on the supplied
     * username.
     * 
     * The authenticate method then calculates a SHA1 hash and
     * compares the result to the SHA1 hash returned by the database
     * 
     * @return boolean whether authentication succeeds.
     */
    public function authenticate()
    {
        $user = Users::model()->findByAttributes(array('username'=>$this->username));
        if ($user === null) {
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        } else if ($user->password !== SHA1($this->password)) {
            //Supplied password does not match the password in the database
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        } else {
            //Supplied password does match the password in the database
            $this->errorCode=self::ERROR_NONE;
            $auth=Yii::app()->authManager;
            $this->username=$user->username; //Save user's username to his session
            if(!$auth->isAssigned($user->role,$this->username)) {
                if($auth->assign($user->role,$this->username)) //Assign user's role
                {
                    Yii::app()->authManager->save(); //Save user's session
                }
            }
        }
        return !$this->errorCode;
    }
}